package com.c.cojbackendquestionservice.manager.impl;

import com.c.cojbackendcommon.common.AiQuestionConstant;
import com.c.cojbackendcommon.common.ErrorCode;
import com.c.cojbackendcommon.exception.BusinessException;
import com.c.cojbackendmodel.model.vo.AiQuestionVO;
import com.c.cojbackendquestionservice.manager.AiModel;

import com.volcengine.ark.runtime.model.completion.chat.ChatCompletionRequest;
import com.volcengine.ark.runtime.model.completion.chat.ChatCompletionResult;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessage;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessageRole;
import com.volcengine.ark.runtime.service.ArkService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Slf4j
@Component
@ConfigurationProperties(prefix = "doyin.doubao")
@Data
public class DouBao implements AiModel {

    private final String DEFAULT_MODEL = "doubao-1-5-lite-32k-250115";

    String apiKey;
    private ArkService service;

    @PostConstruct  // 确保在 apiKey 注入后初始化
    public void init() {
        Objects.requireNonNull(apiKey, "豆包 API Key 不能为空！");
        this.service = new ArkService(apiKey);
        log.info("豆包 AI 服务初始化完成，模型: {}", DEFAULT_MODEL);
    }

    /**
     * 调用 AI 接口，获取响应字符串
     * 只要用户信息，在前端没有输入的情况下
     *
     * @param userPrompt
     * @return
     */
    public String doChat(String userPrompt) {
        return doChat("", userPrompt, DEFAULT_MODEL);
    }

    /**
     * 调用 AI 接口，获取响应字符串
     * 有系统预设以及用户信息
     *
     * @param systemPrompt
     * @param userPrompt
     * @return
     */
    public String doChat(String systemPrompt, String userPrompt) {
        return doChat(systemPrompt, userPrompt, DEFAULT_MODEL);
    }

    /**
     * 调用 AI 接口，获取响应字符串
     *
     * @param systemPrompt
     * @param userPrompt
     * @param model
     * @return
     */
    public String doChat(String systemPrompt, String userPrompt, String model) {
        // 构造消息列表
        try {

            final List<ChatMessage> messages = new ArrayList<>();
            final ChatMessage systemMessage = ChatMessage.builder().role(ChatMessageRole.SYSTEM).content(systemPrompt).build();
            final ChatMessage userMessage = ChatMessage.builder().role(ChatMessageRole.USER).content(userPrompt).build();
            messages.add(systemMessage);
            messages.add(userMessage);

            ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
                    .model(model)
                    .messages(messages)
                    .build();
            ChatCompletionResult response = service.createChatCompletion(chatCompletionRequest);
            // 检查是否有响应结果
            if (response.getChoices() == null || response.getChoices().isEmpty()) {
                // shutdown service,关闭服务
                service.shutdownExecutor();
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "AI 调用成功，但没有返回结果");
            }
            String content= (String) response.getChoices().get(0).getMessage().getContent();
            // shutdown service,关闭服务
            service.shutdownExecutor();
            return content;
        } catch (Exception e) {
            e.printStackTrace();
            service.shutdownExecutor();
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "AI 调用失败，没有返回结果");
        }

    }

    @Override
    public AiQuestionVO getGenResult(String title, String content, String language, Long questionId) {
        String promote = AiQuestionConstant.PRECONDITION + "标题 " + title + " \n内容: " + content + "\n编程语言: " + language;
        String resultData = doChat(promote);
        log.info("调用DeepSeek的AI 生成的信息: {}", resultData);
        String genResult = null;
        String genCode = resultData;
        if (resultData.split("【【【【【").length >= 3) {
            genResult = resultData.split("【【【【【")[1].trim();
            genCode = resultData.split("【【【【【")[2].trim();
        }
        return new AiQuestionVO(genResult, genCode, questionId);
    }
}
